﻿using System;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using System.Text;
using T.ServiceComponent.I18N.Service;

namespace T.FAS.Runtime.Base.Dao
{
    public class ELBDaoFactory<T> : IDaoFactory<T>
    {
        private T instance;

        private string dbName = "TFAS";
        public string DBName
        {
            get
            {
                return dbName;
            }
            set
            {
                if (!string.IsNullOrEmpty(value))
                    dbName = value;
            }
        }

        public T Instance { 
            get 
            {
                if(instance == null)
                {
                    instance = GetDaoInstance();
                }
                return instance;
            }
        }

        public T GetDao()
        {
            return Instance;
        }

        private T GetDaoInstance()
        {
            Type type = typeof(T);
            //默认只有一个ELB类型Dao实现
            Type implementType = type.Assembly
                                .GetTypes()
                                .Where(t => t.GetInterfaces().Contains(type))
                                .FirstOrDefault();
            if (implementType == null)
                throw new Exception($"{TermService.Current.GetTextFormatted("T_FAS_fasr_Base_408665633", "程序集{0}中未找到接口类型{1}的实现", type.Assembly, type)}");
            T instance = (T)Activator.CreateInstance(implementType);

            var baseType = implementType.BaseType;
            var prop = baseType.GetProperty("DBName");
            if (prop == null)
                throw new Exception($"{TermService.Current.GetTextFormatted("T_FAS_fasr_Base_1301385637", "接口类型{0}的实现类{1}不包含DBName属性", type, implementType)}");
            var dbnamevalue = prop.GetValue(instance) as string;
            if (string.IsNullOrWhiteSpace(dbnamevalue))
                prop.SetValue(instance, DBName);
            return instance;
        }
    }
}
